//
//  ShoppingCartVC.m
//  WoWeiRenRenOC
//
//  Created by 姜孟东 on 2020/6/13.
//  Copyright © 2020 姜孟东. All rights reserved.
//

#import "ShoppingCartVC.h"
#import "BusinessModel.h"
#import "HomeIconModel.h"
#import "WebVC.h"
#import "RegisterPayVC.h"
#import "MailCell.h"
#import "BusinessDetailedVC.h"
#import "ShoppingCartHeadView.h"
#import "AbulkCell.h"
#import "ShoppingCartGroupHeadView.h"
#import "ShoppingCartCell.h"
#import "ShoppingCartBottomView.h"
#import "ShoppingCartModel.h"
#import "MailConfirmOrderVC.h"
#import "PagingViewController.h"
#import "ShoppingCarJumpLoginCell.h"
#import "LoginVC.h"
#import "MailDetailsVC.h"

extern UserModel *userModel;
@interface ShoppingCartVC ()

@property (nonatomic,strong) ShoppingCartHeadView *headView;
@property (strong, nonatomic)ShoppingCartBottomView *bottomView;
@property (assign, nonatomic)BOOL isSelectorDelete;
@end

@implementation ShoppingCartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.defaultStartPage = 1;
    self.title = @"购物车";
    [self creatTableViewStyle:UITableViewStyleGrouped cellIdentity:@"ShoppingCartCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ShoppingCarJumpLoginCell" bundle:nil] forCellReuseIdentifier:@"ShoppingCarJumpLoginCell"];
    self.tableView.backgroundColor = kRGBColor(246, 246, 246);
    self.tableView.rowHeight = 120;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.frame = CGRectMake(0, NavBarHeight + 60, kScreenW, kScreenH-TabBarHeight+StatusViewHeight-NavBarHeight-60-50);
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upDateShoppingCarList) name:kUserAddShopingCartUpDate object:nil];

    
    if ([CommonTTool isJumpLoginVC:NO]) {
        [self setRefresh];
           
        SVPShowInternetWaiting
        [self requestData];
        [self.view addSubview:self.headView];
        [self.view addSubview:self.bottomView];
        self.tableView.frame = CGRectMake(0, NavBarHeight + 60, kScreenW, kScreenH-TabBarHeight+StatusViewHeight-NavBarHeight-60-50);
    }else   {
        self.tableView.frame = CGRectMake(0, NavBarHeight, kScreenW, kScreenH-TabBarHeight+StatusViewHeight-NavBarHeight);
    }
    
}

- (void)upDateShoppingCarList {
    self.page = 1;
    [self requestData];
}

- (ShoppingCartHeadView *)headView {
    
    if (!_headView) {
        
        _headView = [[NSBundle mainBundle] loadNibNamed:@"ShoppingCartHeadView" owner:self options:nil].lastObject;
        _headView.frame = CGRectMake(0, NavBarHeight, kScreenW, 60);
        [_headView.ManageBtn addTarget:self action:@selector(manageBtnClick) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    return _headView;
}




- (ShoppingCartBottomView *)bottomView {
    
    if (!_bottomView) {
        
        _bottomView = [[NSBundle mainBundle] loadNibNamed:@"ShoppingCartBottomView" owner:self options:nil].lastObject;
        _bottomView.frame = CGRectMake(0, kScreenH - TabBarHeight - 50, kScreenW, 50);
        [_bottomView.allSelectorBtn addTarget:self action:@selector(allSelectorBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView.settlementBtn addTarget:self action:@selector(settlementBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _bottomView;
}
#pragma mark - 结账或删除按钮点击
- (void)settlementBtnClick {
    
    if (self.isSelectorDelete) {
        [self deleteGoodsHttp];
    }else {
        [self settlementClick];
    }
    
    
}

- (void)deleteGoodsHttp {
    
    NSString *shopping_car_ids = @"";
    for (ShoppingCartModel *model in self.dataArray) {
       for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
           if (childModel.isSelector) {
               shopping_car_ids = [NSString stringWithFormat:@"%@%@,",shopping_car_ids,childModel.shopping_car_id];
           }
       }
    }
    shopping_car_ids = [shopping_car_ids substringWithRange:NSMakeRange(0, [shopping_car_ids length] - 1)];

    SVPShowInternetWaiting;
    [NetRequestTool postUrl:@"shoppingCar/deleteShoppingCar" parameters:@{@"shopping_car_ids":shopping_car_ids} success:^(id responseObject) {
        self.page = 1;
        [self requestData];
    } failure:^(NSInteger statusCode) {
        
    } finish:^{
            
    }];
    
}

#pragma mark - 进入结算界面
- (void)settlementClick {
    
    NSMutableArray *goodS = [NSMutableArray array];
    for (ShoppingCartModel *model in self.dataArray) {
        NSMutableArray *shopping_car_list = [NSMutableArray array];
       for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
           if (childModel.isSelector) {
               
               if (childModel.stock <= 0) {
                   NSString *str = [NSString stringWithFormat:@"%@已没有库存，请重新选择",childModel.sku_name];
                   SVP(str);
                   return;
               }
               if (childModel.state != 1) {
                   NSString *str = [NSString stringWithFormat:@"%@已失效，请重新选择",childModel.sku_name];
                   SVP(str);
                   return;
               }
               if (childModel.sku_type == 2) {
                     NSString *deadlineStr = childModel.end_time;
                    // 当前时间的时间戳
                    NSString *nowStr = [CommonTTool getCurrentTimeyyyymmdd];
                    // 计算时间差值
                    NSInteger secondsCountDown = [CommonTTool getDateDifferenceWithNowDateStr:nowStr deadlineStr:deadlineStr];
                   if (secondsCountDown <= 0 ) {
                        NSString *str = [NSString stringWithFormat:@"%@已失效，请重新选择",childModel.sku_name];
                        SVP(str);
                        return;
                   }
                   if (childModel.tg_order_num > 100) {
                        NSString *str = [NSString stringWithFormat:@"%@已失效，请重新选择",childModel.sku_name];
                        SVP(str);
                        return;
                       
                   }
                   
               }
               [shopping_car_list addObject:childModel];
           }
           
       }
        if (shopping_car_list.count != 0) {
            model.shopping_car_list = shopping_car_list;
            [goodS addObject:model];
        }
    }
    
    if (goodS.count == 0) {
        SVP(@"请选择结算商品");
        return;
    }
    
    NSString *shopping_car_ids = @"";
       for (ShoppingCartModel *model in self.dataArray) {
          for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
              if (childModel.isSelector) {
                  shopping_car_ids = [NSString stringWithFormat:@"%@%@,",shopping_car_ids,childModel.shopping_car_id];
              }
          }
       }
       shopping_car_ids = [shopping_car_ids substringWithRange:NSMakeRange(0, [shopping_car_ids length] - 1)];
    
    MailConfirmOrderVC *vc = [[MailConfirmOrderVC alloc]init];
    vc.modelArray = goodS;
    vc.shopping_car_ids = shopping_car_ids;
    [self.navigationController pushViewController:vc animated:YES];
    
    
    
}



#pragma mark - 购物车全选
- (void)allSelectorBtnClick:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    for (ShoppingCartModel *model in self.dataArray) {
        if (btn.selected) {
            model.isSelector = YES;
            for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
                childModel.isSelector = YES;
            }
            [self.tableView reloadData];
        }else {
            model.isSelector = NO;
            for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
                childModel.isSelector = NO;
            }
            [self.tableView reloadData];
        }
    }
    [self refreshPriceAndCount];

}


#pragma mark - 管理按钮点击
- (void)manageBtnClick {
    
    if (!self.isSelectorDelete) {
        self.isSelectorDelete = YES;
        [self.headView.ManageBtn setTitle:@"完成" forState:UIControlStateNormal];
//        [self.bottomView.settlementBtn setTitle:@"删除" forState:UIControlStateNormal];
        
        
    }else {
        self.isSelectorDelete = NO;
        [self.headView.ManageBtn setTitle:@"管理" forState:UIControlStateNormal];
//        [self.bottomView.settlementBtn setTitle:@"结算" forState:UIControlStateNormal];
        
    }
    for (ShoppingCartModel *model in self.dataArray) {
        
       for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
           
           childModel.isSelector = NO;
       }
    }
    
    [self refreshPriceAndCount];
    
}



- (void)requestData
{
    SVPShowInternetWaiting;
    // 请求列表
    WeakSelf(ws)
    [NetRequestTool postUrl:@"shoppingCar/queryShoppingCarList" parameters:@{@"page":@(self.page), @"limit":@"10",@"type":@"1"} success:^(id responseObject) {
       
        if (self.page == 1) {
            ws.dataArray = [ShoppingCartModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
            
        }else {
            NSArray *newArray = [ShoppingCartModel mj_objectArrayWithKeyValuesArray:responseObject[@"object"]];
            [ws.dataArray addObjectsFromArray:newArray];
        }
        [self refreshPriceAndCount];
        // 控制页数
        NSDictionary *page = [responseObject objectForKey:@"page"];
        if ([page isKindOfClass:NSDictionary.class]) {
            NSInteger totalP = [page[@"total_page"] integerValue];
//            NSInteger totalCount = [page[@"total_count"] integerValue];
            if (totalP > self.page) {
                self.page++;
                [self endRefresh];
            }
            else {
                [self endRefreshNoMoreData];
            }
        }
        else {
            [self endRefreshNoMoreData];
            self.headView.totalLabel.text = [NSString stringWithFormat:@"共0件商品"];

        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [ws.tableView  reloadData];
        });
        
    } failure:^(NSInteger statusCode) {
        [ws endRefreshNoMoreData];
    } finish:^{
        SVPDismiss
    }];
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if ([CommonTTool isJumpLoginVC:NO]) {
        ShoppingCartCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShoppingCartCell"];

        ShoppingCartModel *model = self.dataArray[indexPath.section];
        cell.business_id = model.business_id;
        cell.model = model.shopping_car_list[indexPath.row];
        
        
        cell.refreshPric = ^{
            [self refreshPriceAndCount];
        };
        
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else {
        
        ShoppingCarJumpLoginCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ShoppingCarJumpLoginCell"];
        [cell.jumpLoginBtn addTarget:self action:@selector(jumpLoginClick) forControlEvents:UIControlEventTouchUpInside];
        tableView.rowHeight = kScreenH-TabBarHeight+StatusViewHeight-NavBarHeight;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        return cell;

    }
    
}

- (void)jumpLoginClick {
    
    LoginVC *vc = [[LoginVC alloc]initWithNibName:@"LoginVC" bundle:nil];
    [[CommonTTool getCurrentVC].navigationController pushViewController:vc animated:YES];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (![CommonTTool isJumpLoginVC:NO]) {
        return;
    }
    
    ShoppingCartModel *model = self.dataArray[indexPath.section];
    ShoppingCartGoodsMode *childModel =  model.shopping_car_list[indexPath.row];
    if (childModel.state != 1) {
        NSString *str = [NSString stringWithFormat:@"%@已失效，请重新选择",childModel.sku_name];
        SVP(str);
        return;
    }
    if (childModel.sku_type == 2) {
        NSString *deadlineStr =childModel.end_time;
        // 当前时间的时间戳
        NSString *nowStr = [CommonTTool getCurrentTimeyyyymmdd];
        // 计算时间差值
        NSInteger secondsCountDown = [CommonTTool getDateDifferenceWithNowDateStr:nowStr deadlineStr:deadlineStr];
        if (secondsCountDown <= 0 ) {
           NSString *str = [NSString stringWithFormat:@"%@已失效，请重新选择",childModel.sku_name];
           SVP(str);
           return;
        }
        if (childModel.tg_order_num > 100) {
           NSString *str = [NSString stringWithFormat:@"%@已失效，请重新选择",childModel.sku_name];
           SVP(str);
           return;
          
        }

    }
    
    MailDetailsVC *vc = [[MailDetailsVC alloc] init];
    vc.goodsModel = childModel;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    ShoppingCartGroupHeadView *headView = [[NSBundle mainBundle] loadNibNamed:@"ShoppingCartGroupHeadView" owner:self options:nil].lastObject;
    headView.clipsToBounds = YES;
    ShoppingCartModel *model = self.dataArray[section];
    headView.nameLabel.text = model.business_name;
    [headView.selectorBtn addTarget:self action:@selector(selectorGroupBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    headView.selectorBtn.tag = section;
    if (model.isSelector) {
       headView.selectorBtn.selected = YES;
    }else {
       headView.selectorBtn.selected = NO;
    }
    headView.jumpBtn.tag = section;
    [headView.jumpBtn addTarget:self action:@selector(headVieTapClick:) forControlEvents:UIControlEventTouchUpInside];
    headView.tag = section;
    return headView;
}

- (void)headVieTapClick:(UIButton *)view {
    ShoppingCartModel *model = self.dataArray[view.tag];
    PagingViewController *vc= [[PagingViewController alloc]init];
    vc.business_id = model.business_id;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - 购物车组头选中
- (void)selectorGroupBtnClick:(UIButton *)btn {
    
    btn.selected = !btn.selected;
    ShoppingCartModel *model = self.dataArray[btn.tag];
    
    if (btn.selected) {
        model.isSelector = YES;
        for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
            childModel.isSelector = YES;
            [self.tableView reloadData];
        }
        
    }else {
        model.isSelector = NO;
        for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
            childModel.isSelector = NO;
            [self.tableView reloadData];
        }
        
    }
    
    [self refreshPriceAndCount];

    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    if (![CommonTTool isJumpLoginVC:NO]) {
                
        return 0.01;
    }
    return 35.0f;
}


- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc]init];
    view.backgroundColor = kRGBColor(246, 246, 246);

    return view;;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 10.0f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  {
    if (![CommonTTool isJumpLoginVC:NO]) {
                
        return 1;
    }
    ShoppingCartModel *model = self.dataArray[section];
    return model.shopping_car_list.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    
    if (![CommonTTool isJumpLoginVC:NO]) {
                
        return 1;
    }
    
    return self.dataArray.count;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([CommonTTool isJumpLoginVC:NO]) {

        [self requestData];
       
    }else   {

    }
    
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}


- (void)refreshPriceAndCount {
    
    int goodsCount = 0;
    int selectorgoodCount = 0;
    float goodsAllPrice = 0;
    BOOL bottomSelector = YES;
    for (ShoppingCartModel *model in self.dataArray) {
        BOOL isAllSele = YES;
       for (ShoppingCartGoodsMode *childModel in model.shopping_car_list) {
           goodsCount += 1;
           if (childModel.isSelector) {
               selectorgoodCount += 1;
               if (childModel.is_yk == 2) {
                   goodsAllPrice += childModel.num *childModel.yk_price;
               }else if (childModel.sku_type == 2) {
                   goodsAllPrice += childModel.num *childModel.buy_price;
               }else {
                   goodsAllPrice += childModel.num *childModel.vip_price;
               }
           }else {
               isAllSele = NO;
           }
       }
        if (isAllSele) {
            model.isSelector = YES;
            self.bottomView.allSelectorBtn.selected = YES;
        }else {
            model.isSelector = NO;
            self.bottomView.allSelectorBtn.selected = NO;
            bottomSelector = NO;
        }
    }
    if (self.dataArray.count == 0) {
        bottomSelector = NO;
    }
    if (bottomSelector) {
        self.bottomView.allSelectorBtn.selected = YES;
    }else {
        self.bottomView.allSelectorBtn.selected = NO;

    }
    
    if (self.isSelectorDelete) {
        [self.bottomView.settlementBtn setTitle:[NSString stringWithFormat:@"删除(%d)",selectorgoodCount] forState:UIControlStateNormal];
        self.bottomView.priceLabel.text = [CommonTTool getPrice:goodsAllPrice];
    }else {
        [self.bottomView.settlementBtn setTitle:[NSString stringWithFormat:@"结算(%d)",selectorgoodCount] forState:UIControlStateNormal];
        self.bottomView.priceLabel.text = [CommonTTool getPrice:goodsAllPrice];
    }
    self.headView.totalLabel.text = [NSString stringWithFormat:@"共%d件商品",goodsCount];
    
    [self.tableView reloadData];
}



@end
